package com.weipai.springboot.module.dao.impl;

import com.alibaba.fastjson.JSON;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.weipai.springboot.enums.RetCode;
import com.weipai.springboot.model.WxPay;
import com.weipai.springboot.model.api.Response;
import com.weipai.springboot.module.dao.WxPayDao;
import com.weipai.springboot.util.AliPayUtil;
import org.springframework.stereotype.Repository;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;

/**
 * @Author: 曹朋飞
 * @Date: 2018/09/13 10:56
 */
@Repository
public class WxPayDaoImpl implements WxPayDao{

    //请求XML
    @Override
    public String getRequestXml(Map<Object, Object> parameters) {
        Collection<Object> keyset= parameters.keySet();

        List list=new ArrayList<Object>(keyset);

        Collections.sort(list);
        SortedMap<Object,Object> map2 = new TreeMap<Object, Object>();

        for(int i=0;i<list.size();i++){
            map2.put(list.get(i),parameters.get(list.get(i)));
        }

        StringBuffer sb = new StringBuffer();
        sb.append("<xml>");
        Set es = map2.entrySet();
        Iterator it = es.iterator();
        while(it.hasNext()) {

            Map.Entry entry = (Map.Entry)it.next();
            String key = (String)entry.getKey();
            Object value = (Object)entry.getValue();
            if("total_fee".equalsIgnoreCase(key)){
                sb.append("<"+key+">"+value+"</"+key+">");
            }else{
                sb.append("<"+key+">"+"<![CDATA["+value+"]]></"+key+">");
            }
        }
        sb.append("</xml>");
        return sb.toString();
    }

    //获取统一下单接口返回数据
    @Override
    public Response wxPayReturn(String s, WxPay wp) {
        Response response = new Response();
        Integer a = s.indexOf("<prepay_id><![CDATA[");
        Integer b = s.indexOf("]]></prepay_id>");
        System.out.println(a+"    "+b);
        if(a==-1){
            Map<String, Object> map = new HashMap<>();
            map.put("-1","签名错误，请联系管理员");
            response.setData(map);
            return response;
        }
        wp.setPrepayId(s.substring(a+20,b));
        String sign = wp.Sign(wp);
        wp.setSign(sign);
        String json = JSON.toJSONString(wp);
        response.setCode(RetCode.SUCCESS);
        response.put("data", JSON.parseObject(json));
        return response;
    }

    //访问微信
    @Override
    public String httpsRequest(String requestUrl, String requestMethod, String outputStr) {
        try {//网络请求数据流 并返回数据
            URL url = new URL(requestUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            // 设置请求方式（GET/POST）
            conn.setRequestMethod(requestMethod);
            conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");

            // 当outputStr不为null时向输出流写数据
            if (null != outputStr) {
                OutputStream outputStream = conn.getOutputStream();
                // 注意编码格式
                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            }
            System.out.println("---------------outputStr--------------------"+outputStr);

            // 从输入流读取返回内容
            InputStream inputStream = conn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            StringBuffer buffer = new StringBuffer();
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            // 释放资源
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            inputStream = null;
            conn.disconnect();
            return buffer.toString();
        } catch (ConnectException ce) {
            System.out.println("连接超时：{}"+ ce);
        } catch (Exception e) {
            System.out.println("https请求异常：{}"+ e);
        }
        return null;
    }

    @Override
    public boolean withdrawals(String alipayName, String rrNumber, String money, String type) {
        if("alipay".equals(type)){
            /*支付宝提现*/
            AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
            model.setBody("支付宝提现");
            model.setSubject("支付宝提现");
            model.setOutTradeNo(rrNumber);
            model.setTimeoutExpress("30m");
            model.setTotalAmount(String.valueOf(money));
            model.setProductCode("QUICK_MSECURITY_PAY");
            String sign = AliPayUtil.creatSign(model);

            Map<String, String> map = new HashMap<String, String>();
            map.put("out_biz_no", rrNumber);
            map.put("payee_type", "ALIPAY_LOGONID");
            map.put("alipayName", alipayName);
            map.put("amount", money);
            map.put("payer_show_name", "工老大提现");

            AliPayUtil.invoking(map);
        }
        return false;
    }


}
